package com.example.spider.testing;

import com.jayway.jsonpath.JsonPath;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import okhttp3.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.util.List;


public class OcrUtil {

    /**
     * 模型
     * https://tesseract-ocr.github.io/tessdoc/Data-Files.html
     * 只下载英文包 https://github.com/tesseract-ocr/tessdata_best/blob/main/eng.traineddata
     */
    private static final String tesseractDataPath = "F:\\data\\tessdata_best-4.1.0";

    private static final String language = "eng";

    public static ITesseract iTesseract = null;

    static {
        init();
    }

    private static void init() {
        iTesseract = new Tesseract();
        iTesseract.setDatapath(tesseractDataPath);
        iTesseract.setLanguage(language);
        //iTesseract.setConfigs(List.of("digit"));
        //iTesseract.setPageSegMode(ITessAPI.TessPageSegMode.PSM_SINGLE_LINE);
    }

    public static ITesseract getTesseract() {
        return iTesseract;
    }

    public static void main(String[] args) throws TesseractException, IOException {

        //BufferedImage bufferedImage = ImageIO.read(new URL("https://proxy.mimvp.com/common/ygrandimg?id=1&port=MmDihmtvapW12cDgwODAO0O"));
        String imageFilePath = "F:\\spider\\ipProxy\\portImage\\8080.png";
        File file = new File(imageFilePath);
        String result = ocr(file);
        System.out.println(result);
    }

    public static String ocr(File imageFile) throws IOException, TesseractException {
        BufferedImage bufferedImage = ImageIO.read(imageFile);
        return iTesseract.doOCR(bufferedImage);
    }

    public static String httpOcr(String imageUrl) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder().callTimeout(Duration.ofSeconds(30)).build();
        MediaType mediaType = MediaType.parse("multipart/form-data; boundary=----WebKitFormBoundarylj2uupXHm4D8zIPP");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("url", imageUrl)
                .addFormDataPart("language", "eng")
                .addFormDataPart("isOverlayRequired", "true")
                .addFormDataPart("FileType", ".Auto")
                .addFormDataPart("IsCreateSearchablePDF", "false")
                .addFormDataPart("isSearchablePdfHideTextLayer", "true")
                .addFormDataPart("detectOrientation", "false")
                .addFormDataPart("isTable", "false")
                .addFormDataPart("scale", "true")
                .addFormDataPart("OCREngine", "1")
                .addFormDataPart("detectCheckbox", "false")
                .addFormDataPart("checkboxTemplate", "0")
                .build();
        Request request = new Request.Builder()
                .url("https://api8.ocr.space/parse/image")
                .method("POST", body)
                .addHeader("authority", "api8.ocr.space")
                .addHeader("accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("apikey", "5a64d478-9c89-43d8-88e3-c65de9999580")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36")
                .addHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundarylj2uupXHm4D8zIPP")
                .addHeader("origin", "https://ocr.space")
                .addHeader("sec-fetch-site", "same-site")
                .addHeader("sec-fetch-mode", "cors")
                .addHeader("sec-fetch-dest", "empty")
                .addHeader("referer", "https://ocr.space/")
                .addHeader("accept-language", "zh-CN,zh;q=0.9")
                .build();
        Response response = client.newCall(request).execute();
        InputStream in = response.body().byteStream();
        List<String> results = JsonPath.read(in, "$.ParsedResults[0].TextOverlay.Lines[0].LineText");
        return results.get(0);
    }
}
